package com.controller;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JOptionPane;

import com.model.Tarefa;
import com.view.TelaCad;

public class CadController extends Observable implements ActionListener, WindowListener{

	private static CadController cadCont;
	public TelaCad view;

	public CadController(Observer obs) {
		addObserver(obs);
		cadCont = this;
		EventQueue.invokeLater(new Runnable() {			
			@Override
			public void run() {
				view = new TelaCad();
				view.setVisible(true);
				view.setAcListener(cadCont);
				view.addWindowListener(cadCont);
				view.updateTarefasCad();
				view.cbDesc.grabFocus();
			}

		});
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		if(source == view.cbDesc)
			if(view.cbDesc.getSelectedItem() != null) {
				String atual = view.cbDesc.getSelectedItem().toString();
				Tarefa t = DBManager.getTarefa(atual);
				if(t == null)
					view.limpar();
				else
					view.mostrar(t);
			}
		if(source == view.btCad){
			Tarefa t = view.getTarefa();
			if(DBManager.getTarefa(t.getDescricao()) == null)
				DBManager.addNova(t);
			else
				DBManager.updTarefa(t);
			if(DBManager.getTarefa(t.getDescricao()) == null)
				JOptionPane.showMessageDialog(null, "Cadastrado com Sucesso.");
			else
				JOptionPane.showMessageDialog(null, "Atualizado com Sucesso.");
			view.updateTarefasCad();
		}
	}

	@Override
	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowClosing(WindowEvent e) {
		setChanged();
		notifyObservers();
	}

	@Override
	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub
		
	}

}
